package com.shycloud.mido.homework.controller;

import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.homework.mapper.MidoHomeworkMainMapper;
import io.swagger.annotations.Api;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 作业录音操作
 *
 * @author nianhua.jiang
 */
@Slf4j
@Api(tags = "作业录音操作")
@RestController
@AllArgsConstructor
@RequestMapping("/homework/recording")
@ApiIgnore
public class HomeworkRecordingController {

	/** 作业主表 service */
	private final MidoHomeworkMainMapper mainMapper;
	/** 七牛云工具类 */
	private final MinioTemplate minioTemplate;

	/** 七牛云单次最大删除数量 */
	private final static Integer QINIU_MAX_DELETE_COUNT = 1000;

	/**
	 * 删除作业录音文件释放七牛云空间
	 *
	 * @param startTime 开始时间
	 * @param endTime   结束时间
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/7/2 16:58
	 */
	@GetMapping("deleteRecordingSources")
	public R<Boolean> deleteRecordingSources(String startTime, String endTime) {

		//批量删除七牛云文件时限制大小为1000以内

		//获取 URL 集合
		List<String> urls = mainMapper.getHomeworkRecordingUrl(startTime, endTime);
		//提取 URL 数量
		int urlCount = urls.size();
		//1000个为一组,计算出循环数量
		int forCount = (urlCount / 1000) + 1;
		//循环,开始批量删除
		for (int i = 0; i < forCount; i++) {
			System.out.println("第" + (i + 1) + "次循环");
			//初始化URL数组(1000)
			String[] urlAfter = new String[QINIU_MAX_DELETE_COUNT];
			//定义数组下标
			int arrIndex = 0;

			for (int j = i * QINIU_MAX_DELETE_COUNT; j < (QINIU_MAX_DELETE_COUNT * (i + 1)); j++) {
				//循环次数如果等于URL的数量,则跳出循环,以防止数组下标越界
				if (j == urlCount) {
					break;
				}
				//处理 URL 地址,提取七牛云上传所需要的 key
				String str = urls.get(j).substring(0, urls.get(j).indexOf("com/"));
				String key = urls.get(j).substring(str.length() + 4);
				//将key存入七牛云处理数组中,准备执行批量删除
				urlAfter[arrIndex] = key;
				//数组下标自增
				arrIndex++;
			}
			try {
				//调用七牛云删除逻辑,将文件删除
				minioTemplate.deleteBatch("mido-recording-v2", urlAfter);
				minioTemplate.deleteBatch("mido-recording", urlAfter);
				System.out.println("成功处理" + urlCount + "条数据");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return new R<>(true);
	}

}
